const md5Password = require("../utils/password-handler");
const BaseController = require("./base");

class Controller extends BaseController {
	constructor(...args) {
		super(...args);
		this.table = "user";
		this.createRule = {
			username: "string",
			password: "string",
			email: "string",
			phone: "string"
		};
		this.updateRule = this.createRule;
	}

	async create() {
		const { ctx, service } = this;
		ctx.validate(this.createRule, ctx.request.body);
		const data = ctx.request.body;
		data.password = md5Password(data.password);
		const [user] = await this.app.mysql.select("user", {
			where: {
				username: data.username
			}
		});
		if (user) {
			this.error("用户名已存在");
		} else {
			const res = await service.user.create(data);
			res ? this.success(200, "创建成功") : this.error(201, "创建失败");
		}
	}

	async update() {
		const { ctx, service } = this;
		ctx.validate(this.updateRule, ctx.request.body);
		const data = ctx.request.body;
		data.password = md5Password(data.password);
		const { id } = ctx.params;
		data.id = id;
		const [user] = await this.app.mysql.select("user", {
			where: {
				username: data.username
			}
		});
		if (user) {
			this.error("用户名已存在");
		} else {
			const res = await service.user.update(data);
			res ? this.success(200, "更新成功") : this.error(201, "更新失败");
		}
	}

	async getRole() {
		const { ctx, service } = this;
		const { id } = ctx.params;
		const res = await service.user.getRole(id);

		ctx.body = res;
	}

	async setRole() {
		const { ctx, service } = this;
		const body = ctx.request.body;
		await service.user.setRole(body);

		this.success(200, "添加成功");
	}
}

module.exports = Controller;
